<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus"

interface MetaApplyForm {
  companyName: string
  companyEmail: string
  website: string
  timezone: string
  publicLink: string
  metaAppId?: string
  depositUsd: number | null
  licenseFile: File | null
  contactName: string
  phone: string
}

const formRef = ref<FormInstance>()
const form = reactive<MetaApplyForm>({
  companyName: "",
  companyEmail: "",
  website: "",
  timezone: "",
  publicLink: "",
  metaAppId: "",
  depositUsd: null,
  licenseFile: null,
  contactName: "",
  phone: ""
})

const rules: FormRules<MetaApplyForm> = {
  companyName: [{ required: true, message: "请输入公司注册名称", trigger: "blur" }],
  companyEmail: [
    { required: true, message: "请输入公司邮箱", trigger: "blur" },
    { type: "email", message: "邮箱格式不正确", trigger: ["blur", "change"] }
  ],
  website: [
    { required: true, message: "请输入官方网址", trigger: "blur" },
    { pattern: /^https?:\/\/\S+$/, message: "网址格式不正确，应以 http(s):// 开头", trigger: "blur" }
  ],
  timezone: [{ required: true, message: "请输入账户时区", trigger: "blur" }],
  publicLink: [{ required: true, message: "请输入公众号链接", trigger: "blur" }],
  depositUsd: [
    { required: true, message: "请输入预存金额", trigger: "blur" },
    { type: "number", message: "金额必须为数字", trigger: "blur" }
  ],
  licenseFile: [{ required: true, message: "请上传营业执照附件", trigger: "change" }],
  contactName: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$|^\+?[0-9\-\s]{6,20}$/, message: "电话格式不正确", trigger: "blur" }
  ]
}

const uploading = ref(false)
const fileList = ref<Array<{ name: string }>>([])

function handleExceed() {
  ElMessage.warning("仅支持上传 1 个文件")
}

function beforeUpload(file: File) {
  const isPDFOrImg = /pdf|png|jpg|jpeg/i.test(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isPDFOrImg) ElMessage.error("仅支持 PDF/JPG/PNG 文件")
  if (!isLt10M) ElMessage.error("文件大小不能超过 10MB")
  return isPDFOrImg && isLt10M
}

function handleUploadSuccess(_res: unknown, file: any) {
  form.licenseFile = file.raw as File
  fileList.value = [{ name: file.name }]
}

function handleRemove() {
  form.licenseFile = null
  fileList.value = []
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    uploading.value = true
    try {
      // TODO: 调用提交接口
      await new Promise(r => setTimeout(r, 800))
      ElMessage.success("提交成功")
    } finally {
      uploading.value = false
    }
  })
}

function handleReset() {
  formRef.value?.resetFields()
  fileList.value = []
}
</script>

<template>
  <div class="meta-apply">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="180px">
      <el-form-item label="公司注册名称" prop="companyName" class="form-item">
        <el-input v-model="form.companyName" placeholder="请输入公司注册名称" clearable />
      </el-form-item>

      <el-form-item label="公司邮箱" prop="companyEmail" class="form-item">
        <el-input v-model="form.companyEmail" placeholder="请输入公司邮箱" clearable />
      </el-form-item>

      <el-form-item label="官方网址" prop="website" class="form-item">
        <el-input v-model="form.website" placeholder="请输入官方网址（含 http/https）" clearable />
      </el-form-item>

      <el-form-item label="账户时区" prop="timezone" class="form-item">
        <el-input v-model="form.timezone" placeholder="例如：GMT+8 或 Asia/Shanghai" clearable />
      </el-form-item>

      <el-form-item label="公共主页链接" prop="publicLink" class="form-item">
        <el-input v-model="form.publicLink" placeholder="请输入公共主页链接" clearable />
      </el-form-item>

      <el-form-item label="Meta 应用的编号（可选）" prop="metaAppId" class="form-item">
        <el-input v-model="form.metaAppId" placeholder="如有请填写" clearable />
      </el-form-item>

      <el-form-item label="预存金额" prop="depositUsd" class="form-item">
        <div class="amount-field">
          <el-input-number v-model="form.depositUsd" :min="0" :step="10" :precision="2" />
          <span class="currency">usd</span>
        </div>
      </el-form-item>

      <el-form-item label="营业执照附件" prop="licenseFile" class="form-item">
        <el-upload
          class="upload"
          :limit="1"
          :file-list="fileList"
          action="#"
          :auto-upload="false"
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-remove="handleRemove"
        >
          <el-button type="primary">
            选择文件
          </el-button>
          <template #tip>
            <div class="el-upload__tip">
              支持 PDF/JPG/PNG，最大 10MB
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="联系人" prop="contactName" class="form-item">
        <el-input v-model="form.contactName" placeholder="请输入联系人" clearable />
      </el-form-item>

      <el-form-item label="电话" prop="phone" class="form-item">
        <el-input v-model="form.phone" placeholder="请输入联系电话" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="uploading" @click="handleSubmit">
          提交
        </el-button>
        <el-button @click="handleReset">
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.meta-apply {
  border: #dcdfe6 solid 1px;
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  margin: 20px;
}

.form-item {
  width: 40%;
}

.amount-field {
  display: flex;
  align-items: center;
  gap: 8px;

  .currency {
    color: #909399;
  }
}
</style>
